package com.ideal.manage.esms.service.project;

import com.ideal.manage.esms.bean.alarm.Alarm;
import com.ideal.manage.esms.bean.project.AlarmInfo;
import com.ideal.manage.esms.bean.project.ParameterInfo;
import com.ideal.manage.esms.bean.sys.User;
import com.ideal.manage.esms.config.shiro.MyShiroRealm;
import com.ideal.manage.esms.repository.alarm.AlarmRepository;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.project.AlarmInfoRepository;
import com.ideal.manage.esms.util.HttpRequests;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@CacheConfig(cacheNames = "projectCache")
public class AlarmInfoService {
    @Autowired
    private AlarmInfoRepository alarmInfoRepository;
    @Autowired
    private AlarmRepository alarmRepository;
    @Autowired
    private AlarmInfoService alarmInfoService;

    @Cacheable(value = "projectPage")
    public Page<AlarmInfo> findAllAlarmInfo(int pageNum, HttpServletRequest request) {
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        SpecificationOperator operator = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(operator);
        MySpecification<AlarmInfo> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 15, sort);
        Page<AlarmInfo> page = alarmInfoRepository.findAll(mySpecifications, pageable);
        return page;
    }

    public Page<AlarmInfo> findAllAlarmInfo(int pageNum, HttpServletRequest request,int pageSize) {
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        SpecificationOperator operator = new SpecificationOperator("isValid", "1", "EQ");
        operators.add(operator);
        MySpecification<AlarmInfo> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, pageSize, sort);
        Page<AlarmInfo> page = alarmInfoRepository.findAll(mySpecifications, pageable);
        return page;
    }

    //编辑框回显数据
    public AlarmInfo findById(String id) {
        AlarmInfo code = alarmInfoRepository.findOne(id);
        return code;
    }
    //删除
    public void delParameterInfo(String[] ids) {
        List<AlarmInfo> alarmInfos = alarmInfoRepository.findAll(Arrays.asList(ids));
        for (AlarmInfo alarm:alarmInfos
             ) {
            alarm.setIsValid(0);
        }
        alarmInfoRepository.save(alarmInfos);
    }
    //数据导出
    public List<AlarmInfo> findAllAlarmInfos() {

       return alarmInfoRepository.findAlarmInfos();
    }
    //保存
    @CacheEvict(value = "projectPage", allEntries = true)
    public void saveAlarmInfo(String id, String code, String name, Integer objName, Integer objType, Integer source,
                              Integer alarmLev, Integer manageWay, Integer isRecordSoe, Integer soeDuration, Integer isShow,
                              String parameterCode, String operator, String thresholdCode, String alarmCanName) {
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        Date date = new Date();
        AlarmInfo alarmInfo = new AlarmInfo();
        String uuid = "";
        if (id != null) {
            alarmInfo = findById(id);
            alarmInfo.setCreateUser(new User(shiroUser.getId()));
            alarmInfo.setUpdateTime(new Date());
        }else {
            uuid = UUID.randomUUID().toString().replaceAll("-", "");
            alarmInfo.setId(uuid);
            alarmInfo.setCreateTime(date);
            alarmInfo.setCreateUser(new User(shiroUser.getId()));
            alarmInfo.setIsValid(1);
        }
            alarmInfo.setCode(code);
            alarmInfo.setName(name);
            alarmInfo.setObjName(objName);
            alarmInfo.setObjType(objType);
            alarmInfo.setSource(source);
            alarmInfo.setAlarmLev(alarmLev);
            alarmInfo.setManageWay(manageWay);
            alarmInfo.setAlarmCanName(alarmCanName);
        if(isRecordSoe == null){
            isRecordSoe = 0;
        }
        alarmInfo.setIsRecordSoe(isRecordSoe);
        alarmInfo.setSoeDuration(soeDuration);
        if(isShow == null){
            isShow =0;
        }
        alarmInfo.setIsShow(isShow);
        alarmInfo.setParameterCode(parameterCode);
        alarmInfo.setOperator(operator);
        alarmInfo.setThresholdCode(thresholdCode);

        alarmInfoRepository.save(alarmInfo);
    }
    //文件导入
    public String saveImport(List<String[]> list,String flag) {
        List<AlarmInfo> allCode = alarmInfoRepository.findByCode();
        flag = "0";
        //遍历Excel表中的数据
        for (String [] info:list) {
            if(allCode.contains(info[0])){
                flag = "1";
                return flag;
            }
            AlarmInfo ainfo = new AlarmInfo();
            ainfo.setCode(info[0]);
            ainfo.setName(info[1]);
            ainfo.setObjName(Integer.valueOf(info[2]));
            ainfo.setObjType(Integer.valueOf(info[3]));
            ainfo.setSource(Integer.valueOf(info[4]));
            ainfo.setAlarmLev(Integer.valueOf(info[5]));
            ainfo.setManageWay(Integer.valueOf(info[6]));
            ainfo.setIsRecordSoe(Integer.valueOf(info[7]));
            ainfo.setSoeDuration(Integer.valueOf(info[8]));
            ainfo.setIsShow(Integer.valueOf(info[9]));
            ainfo.setParameterCode(info[10]);
            ainfo.setOperator(info[11]);
            ainfo.setThresholdCode(info[12]);


            MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            ainfo.setId(uuid);
            ainfo.setCreateTime(new Date());
            ainfo.setCreateUser(new User(shiroUser.getId()));
            ainfo.setIsValid(1);
            alarmInfoRepository.save(ainfo);
        }
        return flag;
    }

    /**
     * 根据id查找报警内容
     * @param id
     * @return
     */
    public List<Alarm> findAlarmById(String id){
        List<Alarm> alarmList= alarmRepository.findAlarmById(id);
        return alarmList;
    }

    /**
     * 根据变流器id，设备类型找到所配置的过程告警信息
     * @param equipmentType
     * @param id
     * @return
     */
    public List<AlarmInfo> findAlarmInfosByObjName(String equipmentType,String id){
        Integer parameterType = null;
        // 1. 获取所有 需要显示 的测点参数
        switch (equipmentType) { // 需要做这一步是因为 设备管理 表中的设备类型 和 测点参数 表中的设备类型值代表的意义不一致
            case "1":   // 变流器
                parameterType = 4;
                break;
            case "2":   // 电池包
                parameterType = 2;
                break;
            case "3":   // 电池模组
                parameterType = 3;
                break;
            case "4":   // 电池单体
                parameterType = 5;
                break;
        }
        List<AlarmInfo> alarmInfos= alarmInfoRepository.findAlarmInfoByType(parameterType);
        // 报警内容
        List<Alarm> alarmList = alarmInfoService.findAlarmById(id);
        for(AlarmInfo alarmInfo:alarmInfos){
            for(Alarm alarm:alarmList){
                if(alarmInfo.getName().equals(alarm.getAlarmContent())){
                    alarmInfo.setIsWarning(1);
                    break;
                }
            }
        }
        return alarmInfos;
    }

    /**
     * 编号校验
     * @return
     */
    public List<AlarmInfo> findCode() {
       return  alarmInfoRepository.findByCode();
    }
}
